<template>
    <div>
        <!-- 顶部卡片 -->
        <el-card>
            <el-form :inline="true" class="form">  
                <el-form-item label="职位搜索:">
                    <el-input placeholder="请输入搜索职位的关键字" v-model="keyword"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="searchRole" :disabled="keyword?false:true">搜索</el-button>
                    <el-button type="primary" @click="serRefresh">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>
        <!-- 底部卡片 -->
        <el-card style="margin: 10px 0;">
            <el-button type="primary" style="width: 120px;" @click="AddRole">添加角色</el-button>
            <el-table border style="margin: 10px 0;" :data="roleArr">
                <el-table-column label="#" type="index" align="center"></el-table-column>
                <el-table-column label="Id" align="center" prop="id"></el-table-column>
                <el-table-column label="职位名称" align="center" prop="roleName"></el-table-column>
                <el-table-column label="创建时间" align="center" prop="creaeTime"></el-table-column>
                <el-table-column label="更新时间" align="center" prop="updateTime"></el-table-column>
                <el-table-column label="操作" align="center" width="300">
                    <template #="{row}"> 
                        <el-button type="primary" size="small" icon="User" @click="SetPermission(row)">分配权限</el-button>
                        <el-button type="primary" size="small" icon="Edit" @click="updateRole(row)">编辑</el-button>
                        <el-popconfirm :title="`你确定要删除${row.roleName}吗?`" 
                                @confirm="removeRole(row)">
                            <template #reference>
                                <el-button type="danger" size="small" icon="Delete">删除</el-button>
                            </template>
                        </el-popconfirm>
                        
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                v-model:current-page="pageNow"
                v-model:page-size="pageSize"
                :page-sizes="[5,10,15]"
                :background="true"
                layout=" prev, pager, next, jumper,->, sizes,total"
                :total="total"
                @current-change="getRoleData"
                @size-change="sizeChange"
                />

            
        </el-card>
        <!-- 添加职位与更新职位的抽屉 -->
        <el-dialog v-model="dialogVisible" :title="rolePramas.id?'更新职位':'添加职位'">
            <el-form :model="rolePramas" :rules="rules" ref="FormRef">
                <el-form-item label="职位名称:" prop="roleName">
                    <el-input placeholder="请输入职位名称" v-model="rolePramas.roleName"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click=saveRoleData type="primary">确定</el-button>
                <el-button @click="candle" type="primary">取消</el-button>
            </template>
        </el-dialog>
        <!-- 分配角色的抽屉 -->
        <el-drawer v-model="drawerPermission">
            <template #header>
                <h4>分配角色</h4>
            </template>
            <template #default>
                <div>
                    <el-tree
                        ref="tree"
                        style="max-width: 600px"
                        :data="menuDate"
                        show-checkbox
                        node-key="id"
                        :default-expand-all="true"
                        :default-checked-keys="selectArr"
                        :props="defaultProps"
                    />
                </div>
            </template>
            <template #footer>
                <div style="flex: auto">
                    <el-button @click="cancelPermission">取消</el-button>
                    <el-button type="primary" @click="confirmPermission">确定</el-button>
                </div>
            </template>
        </el-drawer>
    </div>
</template>

<script setup lang='ts'>
import { nextTick, onMounted, reactive, ref } from 'vue';
import {reqGetRole,reqAddOrUpdateRole,reqGetPermission,reqUpdateRolePermission,reqDeleteRole} from '@/api/acl/role/index'
import type {roleResponse,Records,rolePermissionData} from '@/api/acl/role/type'
import useSttingStore from '@/store/modules/stting'
import { ElMessage } from 'element-plus';
//当前页
const pageNow=ref<number>(1)
//每页个数
const pageSize=ref<number>(5)
//储存搜索输入框信息
const keyword=ref<string>('')
//储存角色总个数
let total=ref<number|string>()
//储存获取的角色信息的数组
let roleArr=ref<Records[]>([])
//获取stting仓库
const useSttingstore=useSttingStore()
//控制对话框显隐
const dialogVisible=ref<boolean>(false)
//储存新增或更新角色职位的数据
const rolePramas=reactive<Records>({
    roleName:'',
    id:''
})
// 表单实例
const FormRef=ref()
//控制分配角色抽屉的显隐
const drawerPermission=ref<boolean>(false)
//存储树形下拉菜单数据
const menuDate=ref<rolePermissionData[]>([])
//配置选项
const defaultProps = {
  children: 'children',
  label: 'name',
}
const selectArr=ref<number[]>([])
//下拉树组件实例
const tree=ref()
// 组件挂载发送请求一次
onMounted(()=>{
    getRoleData()
})
//获取角色信息请求
const getRoleData=async (pager:number=1)=>{
    pageNow.value=pager
    let result:roleResponse= await reqGetRole(pageNow.value,pageSize.value,keyword.value)
    if(result.code==200){
        total.value=result.data.total,
        roleArr.value=result.data.records
    }

    
}
//每页个数变化触发的回调
const sizeChange=()=>{
    getRoleData()
}
//搜索按钮回调
const searchRole=()=>{
    //调用发送请求获取搜索结果
    getRoleData()
    //清空输入框
    keyword.value=''

}
//重置按钮回调
const serRefresh=()=>{
    useSttingstore.refresh=!useSttingstore.refresh
}
//添加角色按钮回调
const AddRole=()=>{
    //对话框显示
    dialogVisible.value=true
    //清空之前数据
    Object.assign(rolePramas,{
        roleName:'',
        id:''
    })
    //清空表单校验错误信息
    nextTick(()=>{
        FormRef.value.clearValidate()
    })
}
//更新职位
const updateRole=(row:Records)=>{
    //对话框显示
    dialogVisible.value=true
    Object.assign(rolePramas,row)
    //清空表单校验错误信息
    nextTick(()=>{
        FormRef.value.clearValidate()
    })

}
//dialog对话框点击确定按钮回调
const saveRoleData=async ()=>{
    //表单校验不通过就不执行下面的
    await FormRef.value.validate()
    //发送添加角色请求
    let result:roleResponse=await reqAddOrUpdateRole(rolePramas)
    if(result.code==200){
        ElMessage({
            type:'success',
            message:rolePramas.id?'更新成功':'添加成功'
        })
        //dialog对话框隐藏
        dialogVisible.value=false

        //重新获取角色数据
        getRoleData(rolePramas.id?pageNow.value:1)

    }else{
        ElMessage({
            type:'error',
            message:rolePramas.id?'更新失败':'添加失败'
        })
    }
    
}
//取消按钮回调
const candle=()=>{
    //对话框隐藏
    dialogVisible.value=false
}
// roleName校验规则
const validateRoleName=(_rule: any, value: any, callback: any)=>{
    if(value.trim().length>=2){
        callback()
    }else{  
        callback(new Error('角色名称需大于等于2位'))
    }
}
//对话框规则
const rules={
    roleName:[{required: true,validator: validateRoleName, trigger: 'blur' }]
}
//分配角色按钮回调
const SetPermission=async(row:Records)=>{
    //显示分配角色抽屉
    drawerPermission.value=true
    //存储所点击对应的角色的信息
    Object.assign(rolePramas,row)
    //发送请求
    let result=await reqGetPermission((rolePramas.id as number))
    if(result.code==200){
        menuDate.value=result.data
        selectArr.value=filterSelectArr(menuDate.value,[])
    }
    
}
//获取角色拥有的权限,递归获取
const filterSelectArr=(allData:any,initArr:any)=>{
    allData.forEach((item:rolePermissionData) => {
        if(item.allowed&&item.level==4){
            initArr.push(item.id)
        }
        if(item.children.length>0&&item.children){
            filterSelectArr(item.children,initArr)
        }
    })
    return initArr
}

//分配角色抽屉取消按钮
const cancelPermission=()=>{
    //隐藏分配角色抽屉
    drawerPermission.value=false
}
//分配角色抽屉的确定按钮回调
const confirmPermission=async()=>{
    const roleId=rolePramas.id
    //获取选中节点的id
    const arrSelect=tree.value.getCheckedKeys()
    // 获取半选中节点的id
    const arrHalfSelect=tree.value.getHalfCheckedKeys()
    const roleParmas=arrSelect.concat(arrHalfSelect)
    
    // //发送更新请求
    let result:any=await reqUpdateRolePermission((roleId as number),roleParmas)
    if(result.code==200){
        ElMessage({
            type:'success',
            message:'分配成功'
        })
        // //关闭分配抽屉
        drawerPermission.value=false
        //刷新页面
        window.location.reload()
    }else{
        ElMessage({
            type:'error',
            message:'分配失败'
        })
    }
    
    
}
//删除按钮棋盘框确认按钮回调
const removeRole=async(row:Records)=>{
    //发送删除请求
    let result=await reqDeleteRole((row.id as number))
    if(result.code==200){
        ElMessage({
            type:'success',
            message:'删除成功'
        })
        // 重新获取角色数据
        getRoleData(roleArr.value.length>1?pageNow.value:pageNow.value-1)
    }else{
        ElMessage({
            type:'error',
            message:'删除失败'
        })
    }
}

</script>

<style scoped lang='scss'>
.form{
    width: 100%;
    height: 50px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}
</style>